package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 认证方法
     * @param authenticationToken 用户输入的用户名与密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("调用doGetAuthenticationInfo()进行用户认证................");
        //获取用户身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //拿到用户名去数据库查询用户信息
        User user = userService.getUesrByName(token.getUsername());
        //判断用户名是否存在
        if(user == null) throw new UnknownAccountException();   //用户不存在
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException();  //用户被锁定
        //principal：身份
        //credentials：凭证
        //realmName：当前Realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());
        log.info("调用doGetAuthenticationInfo()用户认证结束................");
        return info;
    }


    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取权限信息
        User user = (User)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }


}
